package com.richard.dev.common.activity;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.richard.dev.common.R;
import com.richard.dev.common.databinding.ActivityFfmpegBinding;
import com.richard.library.basic.basic.BasicBindingActivity;
import com.richard.library.basic.basic.uiview.UIView;
import com.richard.library.permission.OnDenied;
import com.richard.library.permission.PEvent;
import com.richard.library.permission.PermissionHelper;
import com.richard.library.permission.ShowRationale;

import java.io.File;

import io.microshow.rxffmpeg.RxFFmpegCommandList;
import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import io.microshow.rxffmpeg.player.MeasureHelper;
import io.microshow.rxffmpeg.player.RxFFmpegPlayerControllerImpl;
import io.microshow.rxffmpeg.player.RxFFmpegPlayerView;
import permissions.dispatcher.PermissionRequest;

/**
 * @author: Administrator
 * @createDate: 2022/4/2 13:50
 * @version: 1.0
 * @description: FFMpeg
 */
@Route(path = "/test/ffmpeg")
public class TestFFMpegActivity extends BasicBindingActivity<ActivityFfmpegBinding> {

    @Override
    public void initLayoutView() {
        setContentView(R.layout.activity_ffmpeg);
    }

    @Override
    public void initData() {
        navigationbar.setVisibility(View.VISIBLE);
        navigationbar.setTitle("FFMpeg");
        navigationbar.setTitleTextViewShow(true);

        //设置播放器内核
        binding.playerView.switchPlayerCore(RxFFmpegPlayerView.PlayerCoreType.PCT_SYSTEM_MEDIA_PLAYER);

        //设置控制层容器 和 视频尺寸适配模式
        binding.playerView.setController(new RxFFmpegPlayerControllerImpl(this), MeasureHelper.FitModel.FM_DEFAULT);
    }

    @Override
    public void bindListener() {
        binding.bvBtn.setOnClickListener((v) -> {
            selectVideo();
        });

        binding.bvCompress.setOnClickListener((v) -> {
            String path = binding.tvText.getText().toString().trim();
            if (TextUtils.isEmpty(path)) {
                getUIView().showMsg("请选择视频文件");
                return;
            }
            startCompress(new File(path));
        });

        binding.bvPlay.setOnClickListener((v) -> {
            String path = binding.tvText.getText().toString().trim();
            if (TextUtils.isEmpty(path)) {
                getUIView().showMsg("请选择视频文件");
                return;
            }
            if (binding.playerView.isPlaying()) {
                binding.bvPlay.setText("暂停");
                binding.playerView.pause();
            } else {
                binding.bvPlay.setText("播放");
                binding.playerView.play(path, false);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        //恢复播放
        binding.playerView.resume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //暂停视频
        binding.playerView.pause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //销毁播放器
        binding.playerView.release();
        if (zipSubscriber != null) {
            zipSubscriber.dispose();
        }
    }

    /**
     * 选择视频
     */
    private void selectVideo() {
        PermissionHelper.init(this)
                .setPermission(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .setOnDenied(new OnDenied() {
                    @Override
                    public void onDenied() {
                        getUIView().showMsg("您拒绝了权限");
                    }
                })
                .setShowRationale(new ShowRationale() {
                    @Override
                    public void showRationale(PermissionRequest request) {
                        getUIView().showMsg("该操作需要授权");
                        request.proceed();
                    }
                })
                .request(new PEvent() {
                    @Override
                    public void run() {
//                        Matisse.from(TestFFMpegActivity.this)
//                                .choose(MimeType.ofAll())
//                                .theme(com.zhihu.matisse.R.style.Matisse_Dracula)
//                                .autoHideToolbarOnSingleTap(true)
//                                .setImageSortField(MediaStore.Images.Media.DATE_MODIFIED)
//                                .captureStrategy(new CaptureStrategy(true, AppContext.getPackageName().concat(".provider"), "images"))
//                                .setOnlyCapture(false)
//                                .maxSelectable(1)
//                                .originalEnable(false)
//                                .maxOriginalSize(10)
//                                .capture(true)
//                                .compress(true)                 //是否开启压缩（只支持图片）
//                                .compressSize(100)              //超过多少KB才压缩图片
//                                .showCompressProgress(true)     //是否开启图片压缩等待提示
//                                .isCrop(true)                   //是否开启裁剪
//                                .cropOutPutMaxWidth(800)        //裁剪输出最大宽度，单位：px
//                                .cropOutPutMaxHeight(800)       //裁剪输出最大高度，单位：px
//                                .cropAspect(1, 1)              //裁剪比例
//                                .forResult(1);
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        ArrayList<SelectedResult> result = Matisse.obtainPathResult(data);
//
//        if (ObjectUtil.isNotEmpty(result)) {
//            binding.tvText.setText(result.get(0).getPath());
//        }
    }

    /**
     * 开始压缩
     */
    private void startCompress(File videoFile) {
        RxFFmpegInvoke.getInstance().exit();
        if (zipSubscriber != null) {
            zipSubscriber.dispose();
        }

        String inputFile = videoFile.getPath();
        String outPutFile = getContext().getExternalCacheDir() + File.separator + "Compress_" + videoFile.getName();

//        LogUtil.d("testtt",RxFFmpegInvoke.getInstance().getMediaInfo(inputFile));

        //ffmpeg  -i  Desktop/input.mp4  -s 1920x1080  -b:v 1M  -r 20  Desktop/output.mp4
        //ffmpeg -i 1920x1040.mp4 -acodec copy -vcodec libx264 -s 960x520 960x520.flv
        //ffmpeg -i D:\test.webm -vf "crop=640:256:0:400" -threads 5 -preset ultrafast -strict -2  D:\test2.mp4
        //-threads 5 -preset ultrafast

        //ffmpeg -i filename.flv -c:v libx264 -crf 19 -strict experimental filename.mp4
        //ffmpeg -y -i /storage/emulated/0/1/input.mp4 -b 2097k -r 30 -vcodec libx264 -preset superfast /storage/emulated/0/1/result.mp4
        //注意：指令和指令值需分开append
        RxFFmpegCommandList cmdlist = new RxFFmpegCommandList();
        cmdlist.append("-y");
        cmdlist.append("-i");
        cmdlist.append(inputFile);
        cmdlist.append("-b");
        cmdlist.append("2097k");
        cmdlist.append("-r");
        cmdlist.append("30");
        cmdlist.append("-vcodec");
        cmdlist.append("libx264");
        cmdlist.append("-preset");
        cmdlist.append("superfast");
        cmdlist.append(outPutFile);

        zipSubscriber = new ZipSubscriber(getUIView());
        RxFFmpegInvoke.getInstance().runCommandRxJava(cmdlist.build()).subscribe(zipSubscriber);

        binding.tvText.setText(outPutFile);
    }

    private ZipSubscriber zipSubscriber;

    private static class ZipSubscriber extends RxFFmpegSubscriber {

        private final UIView uiView;

        private ZipSubscriber(UIView uiView) {
            this.uiView = uiView;
        }

        @Override
        protected void onStart() {
            super.onStart();
            uiView.showLoading();
        }

        @Override
        public void onFinish() {
            uiView.dismissLoading();
            uiView.showMsgDialog("完成", null);
        }

        @Override
        public void onProgress(int progress, long progressTime) {
            uiView.showLoading(String.format("压缩中 %s%% ", progress));
        }

        @Override
        public void onCancel() {
            uiView.dismissLoading();
            uiView.showMsg("已取消");
        }

        @Override
        public void onError(String message) {
            uiView.dismissLoading();
            uiView.showMsgDialog(message, null);
        }
    }
}
